package com.zjsy.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.zjsy.page.PageBean;
import com.zjsy.po.MainNews;
import com.zjsy.po.MainNewsList;
import com.zjsy.po.MainNewsModule;
import com.zjsy.po.Message;
import com.zjsy.service.MainNewsService;

@Controller
public class MainnewsController {
	
	@Autowired
	private MainNewsService mainNewsService;
	
	@RequestMapping("/newsmodule-list")
	public String newsModulelist(HttpServletRequest req,HttpServletResponse resp) {
		
		List<MainNewsModule> list=mainNewsService.findNewsModule("2");
		req.setAttribute("list", list);
		return "newsmodule-list";
	}
	
	
	@RequestMapping("/shuffling_picture")
	public String shuffling_pictureList(HttpServletRequest req,HttpServletResponse resp) throws Exception {
		

		List<MainNewsList> List =mainNewsService.findShufflingNews();
		req.setAttribute("List", List);
		return "shuffling_picture";
	}
	
	
	

	//获取当前页的页码
			private int getPc(HttpServletRequest req){
				int pc =1 ;
				String param = req.getParameter("pc");
				if(param!=null&&!param.trim().isEmpty()){
					try {
						pc = Integer.parseInt(param);
					} catch (RuntimeException e) {
						
					}
				}
				return pc;
			}
			//截取url，页面中的分页导航中要使用它作为超链接的目标
			private String getUrl(HttpServletRequest req){
				String url = req.getRequestURL()+"?"+req.getQueryString();
				//如果url中存在pc参数
				int index = url.lastIndexOf("&pc=");
				//这步的意思是把如果url中存在pc参数的话，就把pc这个参数去掉，因为上面getPc已经获取pc这个变量值
				if(index!=-1){
					url = url.substring(0, index);
				}
				return url;
			}
			

	
	@RequestMapping("/news-list")
	public String newList(HttpServletRequest req,HttpServletResponse resp) throws Exception {
		
		int pc =getPc(req);
		String url=getUrl(req);
		PageBean<MainNewsList> List =mainNewsService.findMainNewsByPage(pc);
		List.setUrl(url);
		req.setAttribute("List", List);
		List<MainNewsModule> firstClassifyList=mainNewsService.findNewsModule("1");
		List<MainNewsModule> secondClassifyList=mainNewsService.findNewsModule("2");
		req.setAttribute("firstClassifyList", firstClassifyList);
		req.setAttribute("secondClassifyList",secondClassifyList);
		return "news-list";
	}
	
	
     @RequestMapping(value = "/searchNews.action")
	public String searchNews(HttpServletRequest req,HttpServletResponse resp) throws Exception {
		
		int pc =getPc(req);
		String firstClassify=req.getParameter("firstClassify");
		System.out.println(firstClassify);
		String secondClassify=req.getParameter("secondClassify");
		System.out.println(secondClassify);
		PageBean<MainNewsList> List =mainNewsService.findMainNewsByDetail(firstClassify, secondClassify, pc);
		String url="http://localhost:8080/zjsy/searchNews.action?firstClassify="+firstClassify+"&"+"secondClassify="+secondClassify;
		List.setUrl(url);
		System.out.println(url);
		req.setAttribute("List", List);
		List<MainNewsModule> firstClassifyList=mainNewsService.findNewsModule("1");
		List<MainNewsModule> secondClassifyList=mainNewsService.findNewsModule("2");
		req.setAttribute("firstClassifyList", firstClassifyList);
		req.setAttribute("secondClassifyList",secondClassifyList);
		return "news-list";
	}
	
	@RequestMapping("/newsmodule-add")
	public String newsModuleAdd() {
		return "newsmodule-add";
	}
	
	
	@RequestMapping("/news-edit")
	public String newsEdit(HttpServletRequest req,HttpServletResponse resp) {
		String id= req.getParameter("id");
		MainNews news=mainNewsService.findMainNewsById(id);
		List<MainNewsModule> firstClassifyList=mainNewsService.findNewsModule("1");
		List<MainNewsModule> secondClassifyList=mainNewsService.findNewsModule("2");
		req.setAttribute("firstClassifyList", firstClassifyList);
		req.setAttribute("secondClassifyList",secondClassifyList);
		req.setAttribute("news", news);
		return "news-edit";
	}
	
	
	@RequestMapping("/shufllingnews-edit")
	public String shufllingNewsEdit(HttpServletRequest req,HttpServletResponse resp) {
		String id= req.getParameter("id");
		MainNews news=mainNewsService.findShufflingNewsById(id);
		List<MainNewsModule> firstClassifyList=mainNewsService.findNewsModule("1");
		List<MainNewsModule> secondClassifyList=mainNewsService.findNewsModule("2");
		req.setAttribute("firstClassifyList", firstClassifyList);
		req.setAttribute("secondClassifyList",secondClassifyList);
		req.setAttribute("news", news);
		return "shuflling_news-edit";
	}
	
	@RequestMapping("/newsmodule-edit")
	public String newsModuleEdit(HttpServletRequest req,HttpServletResponse resp) {
		String id= req.getParameter("id");
		System.out.println(id);
		MainNewsModule module=mainNewsService.findNewsModuleById(id);
		req.setAttribute("module", module);
		return "newsmodule-edit";
	}
	
	
	
	@RequestMapping("/news-add")
	public String newsAdd(HttpServletRequest req,HttpServletResponse resp) {
		List<MainNewsModule> firstClassifyList=mainNewsService.findNewsModule("1");
		List<MainNewsModule> secondClassifyList=mainNewsService.findNewsModule("2");
		req.setAttribute("firstClassifyList", firstClassifyList);
		req.setAttribute("secondClassifyList",secondClassifyList);
		return "news-add";
	}
	
	@RequestMapping("addNewsModule")
	@ResponseBody
	public Message addNewsModule(HttpServletRequest req,HttpServletResponse resp, @RequestBody MainNewsModule mainewsModule) {
		mainNewsService.addNewsModule(mainewsModule);
		return new Message("添加成功");
	
	}

	
	@RequestMapping("updateModule")
	@ResponseBody
	public Message updateModule(HttpServletRequest req,HttpServletResponse resp, @RequestBody MainNewsModule mainnewsMoudle) {
		mainNewsService.updateNewByid(mainnewsMoudle);
		return new Message("更新成功");	
	}
	
	@RequestMapping("updateNews")
	@ResponseBody
	public Message updateNews(HttpServletRequest req,HttpServletResponse resp, @RequestBody MainNews news) {
		mainNewsService.updateNewsByid(news);
		return new Message("更新成功");	
	}
	
	@RequestMapping("updateShufllingNews")
	@ResponseBody
	public Message updateShufllingNews(HttpServletRequest req,HttpServletResponse resp, @RequestBody MainNews news) {
		mainNewsService.updateShufllingNewsByid(news);
		return new Message("更新成功");	
	}
	
	@RequestMapping("deleteNews")
	@ResponseBody
	public Message deleteNews(HttpServletRequest req,HttpServletResponse resp,String id) {
		mainNewsService.deleteNewsByid(id);
		return new Message("删除成功");	
	}
	
	@RequestMapping("addNews")
	@ResponseBody
	public Message addNews(HttpServletRequest req,HttpServletResponse resp, @RequestBody MainNews mainnews) throws UnsupportedEncodingException {
		req.setCharacterEncoding("utf-8");
		mainNewsService.addNews(mainnews);
		return new Message("添加新闻成功");	
	}
	
	
	    @ResponseBody
	    @RequestMapping("/uploadimg")
	    public Map<String, String> upload(MultipartFile photo,HttpServletRequest request) throws IllegalStateException, IOException {
	        Map<String, String> map = new HashMap<String, String>();
	        try {
	        	String path=null;// 文件路径
	            String type=null;// 文件类型
	            String fileName=photo.getOriginalFilename();// 文件原名称
	            System.out.println("源文件名："+fileName);
	            type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;

	            String realPath="C:\\Users\\Administrator\\Desktop\\resource\\images";
	            System.out.println("路径名："+realPath);
	            // 自定义的文件名称
	            String trueFileName=String.valueOf(System.currentTimeMillis())+fileName;
	            // 设置存放图片文件的路径
	            path=realPath+"\\"+trueFileName;
	            System.out.println("存放图片文件的路径:"+path);
	            // 转存文件到指定的路径
	            photo.transferTo(new File(path));
	            System.out.println("文件成功上传到指定目录下");
	        	
	            //存储文件夹
	            String holder = "/images/";

	            //返回客户端的JSON
	            map.put("success", "true");
	            map.put("msg", "成功");
	            //返回服务器地址
	            map.put("file_path",holder + trueFileName);
	            System.out.println(holder + trueFileName);
	          
	        } catch (IOException e) {
	            map.put("success", "false");
	        }
	        return map;
	    }
	    
	    
	    
	
	
//	    @RequestMapping("/uploadimg")
//	    @ResponseBody
//	    public Map<String, String> upload(MultipartFile photo,HttpServletRequest request) throws IllegalStateException, IOException {
//	        Map<String, String> map = new HashMap<String, String>();
//	        try {
//	        	String path=null;// 文件路径
//	            String type=null;// 文件类型
//	            String fileName=photo.getOriginalFilename();// 文件原名称
//	            System.out.println("源文件名："+fileName);
//	            type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
//
//	            String realPath="C:\\Users\\Administrator\\Desktop\\resource\\images";
//	            System.out.println("路径名："+realPath);
//	            // 自定义的文件名称
//	            String trueFileName=String.valueOf(System.currentTimeMillis())+fileName;
//	            // 设置存放图片文件的路径
//	            path=realPath+"\\"+trueFileName;
//	            System.out.println("存放图片文件的路径:"+path);
//	            // 转存文件到指定的路径
//	            photo.transferTo(new File(path));
//	            System.out.println("文件成功上传到指定目录下");
//	        	
//	            //存储文件夹
//	            String holder = "images/";
//
//	            //返回客户端的JSON
//	            map.put("success", "true");
//	            map.put("msg", "成功");
//	            //返回服务器地址
//	            map.put("file_path",request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" + request.getContextPath() + "/" + holder + trueFileName);
//	            System.out.println(666);
//	            System.out.println(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/" + request.getContextPath() + "/" + holder + trueFileName);
//	        } catch (IOException e) {
//	            map.put("success", "false");
//	        }
//	        return map;
//	    }
	
	/**
	 * 个人信息上传
	 * @return {Result}
	 */

	@RequestMapping(value = "/upload/headImg", method = {RequestMethod.POST})
	@ResponseBody
	public Object headImg(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
	    String prefix="";
	    String dateStr="";
	    String url=request.getServerName()+":"+request.getServerPort()+request.getContextPath() ;
	    Map<String,Object> map2=new HashMap<>();
	    Map<String,Object> map=new HashMap<>();
	    //保存上传
	     OutputStream out = null;
	    InputStream fileInput=null;
	    try{
	        if(file!=null){
	            String originalName = file.getOriginalFilename();
	            System.out.println("originalName:"+originalName);
	            prefix=originalName.substring(originalName.lastIndexOf(".")+1);
	            String time=String.valueOf(System.currentTimeMillis());
	            String filepath = "C:\\Users\\Administrator\\Desktop\\resource\\images\\"+time+originalName;
	            System.out.println("图片的路径为"+time+originalName);
	            filepath = filepath.replace("\\", "/");
	            System.out.println(filepath);
	            File files=new File(filepath);
	            //打印查看上传路径
	    
	            if(!files.getParentFile().exists()){
	                files.getParentFile().mkdirs();
	            }
	            file.transferTo(files);
	   
	    	    map.put("code",0);
	    	    map.put("msg","");
	    	    map.put("data",map2);
	    	    map2.put("src","/images/"+time+originalName);
	        }
	    }catch (Exception e){
	    }finally{
	        try {
	            if(out!=null){
	                out.close();
	            }
	            if(fileInput!=null){
	                fileInput.close();
	            }
	        } catch (IOException e) {
	        }
	    }
	  
	    return map;
	}
//  public String photoUpload(@RequestParam(value="file",required=false)MultipartFile file,HttpServletRequest request,String id,HttpSession session) throws IllegalStateException, IOException{
//        
//        if (file!=null) {// 判断上传的文件是否为空
//            String path=null;// 文件路径
//            String type=null;// 文件类型
//            String fileName=file.getOriginalFilename();// 文件原名称
//            System.out.println("上传的文件原名称:"+fileName);
//            // 判断文件类型
//            type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
//            if (type!=null) {// 判断文件类型是否为空
//                if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())||"jpeg".equals(type.toUpperCase())) {
//                   
//                    String realPath=request.getServletContext().getRealPath("/images/");
//                    // 自定义的文件名称
//                    String trueFileName=String.valueOf(System.currentTimeMillis())+fileName;
//                    // 设置存放图片文件的路径
//                    path=realPath+trueFileName;
//                    System.out.println("存放图片文件的路径:"+path);
//                    // 转存文件到指定的路径
//                    file.transferTo(new File(path));
//                    System.out.println("文件成功上传到指定目录下");
////                    boolean updateMessage = messageService.updateMessagepic(student);
////                    if(updateMessage)
//                    	return "success";
//                }else {
//                    System.out.println("不是我们想要的文件类型,请按要求重新上传");
//                    return "errortype";
//                }
//            }else {
//                System.out.println("文件类型为空");
//                return "nulltype";
//            }
//        }else {
//            System.out.println("没有找到相对应的文件");
//            return "nulltype";
//        }
////        return "errortran";
//    }
	
	

}
